package app

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"shorten/pkg/errcode"
	"shorten/pkg/util"
)

// Response 标准化JSON输出
type Response struct {
	Code   int         `json:"code"`
	Msg    string      `json:"msg"`
	Result interface{} `json:"result"`
}

// Success 返回成功的json数据
func Success(c *gin.Context, data interface{}) {
	res := Response{
		Code:   errcode.SUCCESS,
		Msg:    errcode.GetMsg(errcode.SUCCESS),
		Result: data,
	}
	c.JSON(http.StatusOK, res)
	return
}

// Failed 返回失败的json数据
func Failed(c *gin.Context, code int) {
	if code == errcode.SUCCESS {
		panic("状态码错误")
	}
	res := Response{
		Code:   code,
		Msg:    errcode.GetMsg(code),
		Result: struct{}{},
	}
	c.JSON(http.StatusOK, res)
	return
}

func FailedWithMsg(c *gin.Context, code int, msg string) {
	if code == errcode.SUCCESS {
		panic("状态码错误")
	}
	res := Response{
		Code:   code,
		Msg:    util.Ter(msg != "", msg, errcode.GetMsg(code)),
		Result: struct{}{},
	}
	c.JSON(http.StatusOK, res)
	return
}
